package com.xbongbong.paas.script.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.elasticsearch.pojo.XbbAggregatedPage;
import com.xbongbong.paas.elasticsearch.pojo.dto.InsertDTO;
import com.xbongbong.paas.elasticsearch.util.EsHelper;
import com.xbongbong.paas.elasticsearch.util.EsUtil;
import com.xbongbong.paas.elasticsearch.util.XbbElasticsearchRestTemplate;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.help.subform.TransferSubFormHelper;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.pojo.dto.FixDataJobDTO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.Arith;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.pro.config.ProBaseConfig;
import com.xbongbong.pro.constant.ElasticConstant;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.domain.entity.ChartEntity;
import com.xbongbong.pro.domain.entity.UpdateDataEntity;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.formexplain.pojo.vo.FormExplainAddBatchVO;
import com.xbongbong.pro.script.pojo.dto.AllScriptDTO;
import com.xbongbong.pro.script.pojo.dto.FixOldStockExplainDTO;
import com.xbongbong.pro.script.pojo.dto.ProductDTO;
import com.xbongbong.pro.statistic.model.ChartModel;
import com.xbongbong.pro.statistic.pojo.SlaveSourcePojo;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.StockConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.dao.ContractProductDao;
import com.xbongbong.saas.domain.dao.ProductUserDao;
import com.xbongbong.saas.domain.entity.ContractProductEntity;
import com.xbongbong.saas.domain.entity.InstockProductEntity;
import com.xbongbong.saas.domain.entity.OutstockProductEntity;
import com.xbongbong.saas.domain.entity.ProductUserEntity;
import com.xbongbong.saas.domain.entity.ProductWarehouseEntity;
import com.xbongbong.saas.domain.entity.ReturnedPurchaseProductEntity;
import com.xbongbong.saas.domain.entity.SupplierProductEntity;
import com.xbongbong.saas.domain.entity.UpdateStockDataEntity;
import com.xbongbong.saas.domain.entity.ext.ProductEntityExt;
import com.xbongbong.saas.enums.InstockTypeEnum;
import com.xbongbong.saas.enums.OutstockTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.InstockEnum;
import com.xbongbong.saas.enums.business.OutstockEnum;
import com.xbongbong.saas.enums.business.ProductEnum;
import com.xbongbong.saas.enums.business.ProductionOrderEnum;
import com.xbongbong.saas.enums.business.RefundEnum;
import com.xbongbong.saas.enums.business.SupplierEnum;
import com.xbongbong.saas.enums.business.WarehouseEnum;
import com.xbongbong.saas.enums.dictionary.WarehouseOriStockEnum;
import com.xbongbong.saas.model.ContractProductModel;
import com.xbongbong.saas.model.InstockModel;
import com.xbongbong.saas.model.InstockProductModel;
import com.xbongbong.saas.model.OutstockModel;
import com.xbongbong.saas.model.OutstockProductModel;
import com.xbongbong.saas.model.ProductModel;
import com.xbongbong.saas.model.ProductUserModel;
import com.xbongbong.saas.model.ProductWarehouseModel;
import com.xbongbong.saas.model.ProductionOrderModel;
import com.xbongbong.saas.model.ReturnedPurchaseProductModel;
import com.xbongbong.saas.model.SupplierProductModel;
import com.xbongbong.saas.model.WarehouseModel;
import com.xbongbong.saas.script.service.InitExplainsService;
import com.xbongbong.saas.service.RepairExplainService;
import com.xbongbong.sys.model.CompanyModel;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.support.WriteRequest;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.index.query.QueryBuilders.termsQuery;

/**
 * @author feng.zheng
 * @version v1.0
 * @date 2019/10/12 15:15
 * @since v1.0
 */
@RestController
@RequestMapping(XbbProConstant.API_ROOT_PREFIX + "/script/product")
public class ProductScriptController {
    private static final Logger LOG = LoggerFactory.getLogger(ProductScriptController.class);
    @Resource
    private ProBaseConfig proBaseConfig;
    @Resource
    private SupplierProductModel supplierProductModel;
    @Resource
    private EsHelper esHelper;
    @Resource
    private CompanyModel companyModel;
    @Resource
    private ProductModel productModel;
    @Resource
    private ProductWarehouseModel productWarehouseModel;

    @Resource
    private ProductUserModel productUserModel;
    @Resource
    private WarehouseModel warehouseModel;
    @Resource
    private InstockProductModel instockProductModel;
    @Resource
    private OutstockProductModel outstockProductModel;
    @Resource
    private InitExplainsService initExplainsService;
    @Resource
    private XbbElasticsearchRestTemplate xbbElasticsearchRestTemplate;
    @Resource
    private RepairExplainService repairExplainService;
    @Resource
    private InstockModel instockModel;
    @Resource
    private PaasFormExplainModel paasFormExplainModel;
    @Resource
    private ContractProductModel contractProductModel;
    @Resource
    private ReturnedPurchaseProductModel returnedPurchaseProductModel;
    @Resource
    private OutstockModel outstockModel;
    @Resource
    private ProductionOrderModel productionOrderModel;
    @Resource
    private ChartModel chartModel;
    @Resource
    private ContractProductDao contractProductDao;
    @Resource
    private PaasEsModel paasEsModel;
    @Resource
    private ProductUserDao productUserDao;
    @Resource
    private TransferSubFormHelper transferSubFormHelper;

    @RequestMapping(value = "/productAssociationSupplier", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String productAssociationSupplier(@RequestBody @Valid FixDataJobDTO fixDataJobDTO, BindingResult br) throws Exception {
        if (!proBaseConfig.getXbbCode().equals(fixDataJobDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
        }
        long start = DateTimeUtil.getInt();
        List<String> corpidList = fixDataJobDTO.getCorpidList();
        if (CollectionsUtil.isEmpty(corpidList)) {
            corpidList = productModel.getCorpidList();
        }
        LOG.warn("数据库中共有公司" + corpidList.size() + "家");
        int corpidCount = 0;
        for (String corpid : corpidList) {
            Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
            param.put(ParameterConstant.CORPID, corpid);
            Integer totalCount = supplierProductModel.getEntitysCount(param);
            LOG.warn("corpid:" + corpid + "数据库中共有产品供应商" + totalCount + "条数据");
            int pageSize = 1000;
            int totalPage = (totalCount % pageSize == 0) ? (totalCount / pageSize) : (totalCount / pageSize) + 1;
            int lastPageSize = (totalCount % pageSize == 0) ? pageSize : (totalCount % pageSize);
            Set<Long> parentIdSet = new HashSet<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            List<SupplierProductEntity> childSupplierProductList  = new ArrayList<>();
            for (int page = 0; page < totalPage; page++) {
                if (page == totalPage - 1) {
                    param.put("pageNum", lastPageSize);
                } else {
                    param.put("pageNum", pageSize);
                }
                param.put("start", page * pageSize);
                LOG.warn("第" + (page+1) + "页开始");
                List<SupplierProductEntity> supplierProductEntityList = supplierProductModel.findEntitys(param);
                if (supplierProductEntityList.isEmpty()) {
                    continue;
                }
                List<Long> parentIdIn = new ArrayList<>();
                for (SupplierProductEntity supplierProductEntity : supplierProductEntityList) {
                    parentIdIn.add(supplierProductEntity.getProductId());
                    parentIdSet.add(supplierProductEntity.getParentId() == null ? 0L : supplierProductEntity.getParentId());
                }
                BoolQueryBuilder boolQueryBuilder = boolQuery();
                boolQueryBuilder.filter(termQuery(ParameterConstant.CORPID + StringConstant.POINT + StringConstant.KEY_WORD, corpid));
                boolQueryBuilder.filter(termsQuery("data." + ProductEnum.PARENT_ID.getAttr(), parentIdIn));
                List<String> fieldList = new ArrayList<>();
                fieldList.add(StringConstant.SAAS_LINK_BUSINESS_ID);
                fieldList.add("data." + ProductEnum.PARENT_ID.getAttr());
                List<PaasFormDataEntity> childProductList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_PRODUCT, boolQueryBuilder, PaasFormDataEntity.class, fieldList);
                Map<Long, List<Long>> childProductMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                childProductList.forEach(child -> {
                    Long parentId = null;
                    if (Objects.nonNull(child.getData()) && Objects.nonNull(child.getData().getLong(ProductEnum.PARENT_ID.getAttr()))) {
                        parentId = child.getData().getLong(ProductEnum.PARENT_ID.getAttr());
                    }
                    if (Objects.nonNull(parentId)) {
                        List<Long> childIdList  = childProductMap.getOrDefault(parentId, new ArrayList<>());
                        childIdList.add(child.getId());
                        childProductMap.put(parentId, childIdList);
                    }
                });

                for (SupplierProductEntity parent : supplierProductEntityList) {
                    List<Long> childProductIdList = childProductMap.get(parent.getProductId());
                    if (CollectionsUtil.isNotEmpty(childProductIdList)) {
                        for (Long childId : childProductIdList) {
                            SupplierProductEntity supplierProductEntity = new SupplierProductEntity();
                            supplierProductEntity.setParentId(parent.getProductId());
                            supplierProductEntity.setCorpid(parent.getCorpid());
                            supplierProductEntity.setSort(parent.getSort());
                            supplierProductEntity.setSupplierId(parent.getSupplierId());
                            supplierProductEntity.setProductId(childId);
                            childSupplierProductList.add(supplierProductEntity);
                        }
                    }
                }
                LOG.warn("第" + (page+1) + "页结束");
            }
            if (CollectionsUtil.isNotEmpty(childSupplierProductList) && parentIdSet.size() <= 1) {
                int insertTotal = childSupplierProductList.size();
                int insertPageSize = 1000;
                int insertTotalPage = (insertTotal % insertPageSize == 0) ? (insertTotal / insertPageSize) : (insertTotal / insertPageSize) + 1;
                for (int page = 0; page < insertTotalPage; page++) {
                    List<SupplierProductEntity> insertList;
                    if (page == insertTotalPage - 1) {
                        insertList = childSupplierProductList.subList(insertPageSize * page, childSupplierProductList.size());
                    } else {
                        insertList = childSupplierProductList.subList(insertPageSize * page, insertPageSize * (page + 1));
                    }
                    supplierProductModel.batchInsert(insertList);
                }
            }
            ++ corpidCount;
            LOG.warn("公司" + corpidCount + "/" + corpidList.size());
        }
        LOG.warn("consume:" + (DateTimeUtil.getInt() - start));
        LOG.warn("操作成功");
        return null;
    }

    @RequestMapping(value = "/addChildIds", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String addChildIds(@RequestBody @Valid FixDataJobDTO fixDataJobDTO, BindingResult br) throws Exception {
        if (!proBaseConfig.getXbbCode().equals(fixDataJobDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
        }
        long start = DateTimeUtil.getInt();
        List<String> corpidList = fixDataJobDTO.getCorpidList();
        if (CollectionsUtil.isEmpty(corpidList)) {
            corpidList = productModel.getCorpidList();
        }
        LOG.warn("数据库中共有公司" + corpidList.size() + "家");
        int corpidCount = 0;
        for (String corpid : corpidList) {
            Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
            param.put(ParameterConstant.CORPID, corpid);
            param.put("pageSize", 1000);
            param.put("childIdsIsNull", 1);
            param.put("parentId", 0);
            param.put("orderByStr", "id");
            boolean addFlag = true;
            while (addFlag) {
                List<SupplierProductEntity> supplierProductEntityList = supplierProductModel.findEntitys(param);
                if (Objects.isNull(supplierProductEntityList) || supplierProductEntityList.isEmpty()) {
                    addFlag = false;
                } else {
                    LOG.warn("遍历id到" + supplierProductEntityList.get(supplierProductEntityList.size() - 1).getId());
                    param.put("idGte", supplierProductEntityList.get(supplierProductEntityList.size() - 1).getId());
                    List<Long> parentIdIn = new ArrayList<>();
                    for (SupplierProductEntity supplierProductEntity : supplierProductEntityList) {
                        if (Objects.nonNull(supplierProductEntity.getProductId())) {
                            parentIdIn.add(supplierProductEntity.getProductId());
                        }
                    }
                    if (parentIdIn.isEmpty()) {
                        continue;
                    }
                    BoolQueryBuilder boolQueryBuilder = boolQuery();
                    boolQueryBuilder.filter(termQuery(ParameterConstant.CORPID + StringConstant.POINT + StringConstant.KEY_WORD, corpid));
                    boolQueryBuilder.filter(termsQuery("data." + ProductEnum.PARENT_ID.getAttr(), parentIdIn));
                    List<String> fieldList = new ArrayList<>();
                    fieldList.add(StringConstant.SAAS_LINK_BUSINESS_ID);
                    fieldList.add("data." + ProductEnum.PARENT_ID.getAttr());
                    List<PaasFormDataEntity> childProductList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_PRODUCT, boolQueryBuilder, PaasFormDataEntity.class, fieldList);
                    Map<Long, List<Long>> childProductMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    childProductList.forEach(child -> {
                        Long parentId = null;
                        if (Objects.nonNull(child.getData()) && Objects.nonNull(child.getData().getLong(ProductEnum.PARENT_ID.getAttr()))) {
                            parentId = child.getData().getLong(ProductEnum.PARENT_ID.getAttr());
                        }
                        if (Objects.nonNull(parentId)) {
                            List<Long> childIdList = childProductMap.getOrDefault(parentId, new ArrayList<>());
                            childIdList.add(child.getId());
                            childProductMap.put(parentId, childIdList);
                        }
                    });
                    for (SupplierProductEntity supplierProductEntity : supplierProductEntityList) {
                        List<Long> childProductIdList = childProductMap.get(supplierProductEntity.getProductId());
                        if (CollectionsUtil.isNotEmpty(childProductIdList)) {
                            supplierProductEntity.setChildIds(JSON.toJSONString(childProductIdList));
                        }
                    }
                    if (!supplierProductEntityList.isEmpty()) {
                        supplierProductModel.updateBatch(supplierProductEntityList, corpid);
                    }
                }
            }
            ++corpidCount;
            LOG.warn("公司" + corpidCount + "/" + corpidList.size());
        }
        LOG.warn("consume:" + (DateTimeUtil.getInt() - start));
        LOG.warn("操作成功");
        return null;
    }


    /*@RequestMapping(value = "/addChildIds", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String addChildIds(@RequestBody @Valid FixDataJobDTO fixDataJobDTO, BindingResult br) throws Exception {
        if (!proBaseConfig.getXbbCode().equals(fixDataJobDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
        }
        long start = DateTimeUtil.getInt();
        List<String> corpidList = fixDataJobDTO.getCorpidList();
        if (CollectionsUtil.isEmpty(corpidList)) {
            corpidList = productModel.getCorpidList();
        }
        LOG.warn("数据库中共有公司" + corpidList.size() + "家");
        int corpidCount = 0;
        for (String corpid : corpidList) {
            Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
            param.put(ParameterConstant.CORPID, corpid);
            param.put("childIdsIsNull", 1);
            Integer totalCount;
            if (Objects.equals(fixDataJobDTO.getFromProductSupplier(), 1)) {
                totalCount = supplierProductModel.getEntitysCount(param);
            } else {
                totalCount = productUserModel.getEntitysCount(param);
            }
            int pageSize = 1000;
            int totalPage = (totalCount % pageSize == 0) ? (totalCount / pageSize) : (totalCount / pageSize) + 1;
            int lastPageSize = (totalCount % pageSize == 0) ? pageSize : (totalCount % pageSize);
            for (int page = 0; page < totalPage; page++) {
                if (page == totalPage - 1) {
                    param.put("pageNum", lastPageSize);
                } else {
                    param.put("pageNum", pageSize);
                }
                param.put("start", 0);
                LOG.warn("第" + (page+1) + "页开始");
                List<Long> parentIdIn = new ArrayList<>();
                List<SupplierProductEntity> supplierProductEntityList = new ArrayList<>();
                List<ProductUserEntity> productUserEntityList = new ArrayList<>();
                if (Objects.equals(fixDataJobDTO.getFromProductSupplier(), 1)) {
                    supplierProductEntityList = supplierProductModel.findEntitys(param);
                    for (SupplierProductEntity supplierProductEntity : supplierProductEntityList) {
                        parentIdIn.add(supplierProductEntity.getProductId());
                    }
                } else {
                    productUserEntityList = productUserModel.findEntitys(param);
                    for (ProductUserEntity productUserEntity : productUserEntityList) {
                        parentIdIn.add(productUserEntity.getDataId());
                    }
                }
                BoolQueryBuilder boolQueryBuilder = boolQuery();
                boolQueryBuilder.filter(termQuery(ParameterConstant.CORPID + StringConstant.POINT + StringConstant.KEY_WORD, corpid));
                boolQueryBuilder.filter(termsQuery("data." + ProductEnum.PARENT_ID.getAttr(), parentIdIn));
                List<String> fieldList = new ArrayList<>();
                fieldList.add(StringConstant.SAAS_LINK_BUSINESS_ID);
                fieldList.add("data." + ProductEnum.PARENT_ID.getAttr());
                List<PaasFormDataEntity> childProductList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_PRODUCT, boolQueryBuilder, PaasFormDataEntity.class, fieldList);
                Map<Long, List<Long>> childProductMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                childProductList.forEach(child -> {
                    Long parentId = null;
                    if (Objects.nonNull(child.getData()) && Objects.nonNull(child.getData().getLong(ProductEnum.PARENT_ID.getAttr()))) {
                        parentId = child.getData().getLong(ProductEnum.PARENT_ID.getAttr());
                    }
                    if (Objects.nonNull(parentId)) {
                        List<Long> childIdList  = childProductMap.getOrDefault(parentId, new ArrayList<>());
                        childIdList.add(child.getId());
                        childProductMap.put(parentId, childIdList);
                    }
                });
                if (Objects.equals(fixDataJobDTO.getFromProductSupplier(), 1)) {
                    for (SupplierProductEntity parent : supplierProductEntityList) {
                        List<Long> childProductIdList = childProductMap.get(parent.getProductId());
                        if (CollectionsUtil.isNotEmpty(childProductIdList)) {
                            parent.setChildIds(JSON.toJSONString(childProductIdList));
                        }
                    }
                    if (!supplierProductEntityList.isEmpty()){
                        supplierProductModel.updateBatch(supplierProductEntityList, corpid);
                    }
                } else {
                    for (ProductUserEntity productUserEntity : productUserEntityList) {
                        List<Long> childProductIdList = childProductMap.get(productUserEntity.getDataId());
                        if (CollectionsUtil.isNotEmpty(childProductIdList)) {
                            productUserEntity.setChildIds(JSON.toJSONString(childProductIdList));
                        }
                    }
                    if (!productUserEntityList.isEmpty()){
                        productUserDao.updateBatch(productUserEntityList, corpid);
                    }
                }
                LOG.warn("第" + (page+1) + "页结束");
            }
            ++ corpidCount;
            LOG.warn("公司" + corpidCount + "/" + corpidList.size());
        }
        LOG.warn("consume:" + (DateTimeUtil.getInt() - start));
        LOG.warn("操作成功");
        return null;
    }*/

    @RequestMapping(value = "/incProductAssociationUser", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String incProductAssociationUser(@RequestBody @Valid FixDataJobDTO fixDataJobDTO, BindingResult br) throws Exception {
        if (!proBaseConfig.getXbbCode().equals(fixDataJobDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
        }
        long start = DateTimeUtil.getInt();
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(ParameterConstant.DEL, DelEnum.DELETE.getDel());
        param.put("childIdsNotNull", 1);
        param.put(ParameterConstant.PARENT_ID, 0);
        param.put("orderByStr", "id");
        param.put("pageSize", 1000);
        boolean delFlag = true;
        List<Long> parentIdIn = new ArrayList<>();
        List<Object> userRelationIdIn = new ArrayList<>();
        List<Object> deptRelationIdIn = new ArrayList<>();
        while (delFlag) {
            List<ProductUserEntity> productUserEntityList = productUserModel.findEntitys(param);
            if (Objects.isNull(productUserEntityList) || productUserEntityList.isEmpty()) {
                delFlag = false;
            } else {
                LOG.warn("遍历id到" + productUserEntityList.get(productUserEntityList.size() - 1).getId());
                param.put("idGte", productUserEntityList.get(productUserEntityList.size() - 1).getId());

                for (ProductUserEntity productUserEntity : productUserEntityList) {
                    parentIdIn.add(productUserEntity.getDataId());
                    if (Objects.equals(productUserEntity.getType(), 0)) {
                        userRelationIdIn.add(productUserEntity.getRelationId());
                    } else {
                        deptRelationIdIn.add(productUserEntity.getRelationId());
                    }
                }
            }
        }
        if (CollectionsUtil.isNotEmpty(userRelationIdIn)) {
            productUserModel.deleteByParentIdInAndRelationIdInByScript(parentIdIn, userRelationIdIn, 0, new ArrayList<>());
        }
        if (CollectionsUtil.isNotEmpty(deptRelationIdIn)) {
            productUserModel.deleteByParentIdInAndRelationIdInByScript(parentIdIn, deptRelationIdIn, 1, new ArrayList<>());
        }
        param.remove("childIdsNotNull");
        param.remove("parentId");
        param.remove("idGte");
        param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        param.put("childIdsIsNull", 1);
        param.put("parentIdIsNull", 1);
        List<ProductUserEntity> childAddProductUserList = new ArrayList<>();
        List<ProductUserEntity> parentAddProductUserList = new ArrayList<>();
        Set<Long> parentIdSet = new HashSet<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        boolean flag = true;
        while (flag) {
            List<ProductUserEntity> productUserEntityList = productUserModel.findEntitys(param);
            if (Objects.isNull(productUserEntityList) || productUserEntityList.isEmpty()) {
                flag = false;
            } else {
                LOG.warn("遍历id到" + productUserEntityList.get(productUserEntityList.size() - 1).getId());
                param.put("idGte", productUserEntityList.get(productUserEntityList.size() - 1).getId());
                for (ProductUserEntity productUserEntity : productUserEntityList) {
                    if (Objects.nonNull(productUserEntity.getDataId())) {
                        parentIdSet.add(productUserEntity.getDataId());
                    }
                }
                if (parentIdSet.isEmpty()) {
                    continue;
                }
                BoolQueryBuilder boolQueryBuilder = boolQuery();
                boolQueryBuilder.filter(termsQuery("data." + ProductEnum.PARENT_ID.getAttr(), parentIdSet));
                List<String> fieldList = new ArrayList<>();
                fieldList.add(StringConstant.SAAS_LINK_BUSINESS_ID);
                fieldList.add("data." + ProductEnum.PARENT_ID.getAttr());
                List<PaasFormDataEntity> childProductList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_PRODUCT, boolQueryBuilder, PaasFormDataEntity.class, fieldList);
                Map<Long, List<Long>> childProductMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                childProductList.forEach(child -> {
                    Long parentId = null;
                    if (Objects.nonNull(child.getData()) && Objects.nonNull(child.getData().getLong(ProductEnum.PARENT_ID.getAttr()))) {
                        parentId = child.getData().getLong(ProductEnum.PARENT_ID.getAttr());
                    }
                    if (Objects.nonNull(parentId)) {
                        List<Long> childIdList = childProductMap.getOrDefault(parentId, new ArrayList<>());
                        childIdList.add(child.getId());
                        childProductMap.put(parentId, childIdList);
                    }
                });
                ProductUserEntity userEntity;
                for (ProductUserEntity productUserEntity : productUserEntityList) {
                    if (CollectionsUtil.isNotEmpty(childProductMap.get(productUserEntity.getDataId()))) {
                        productUserEntity.setParentId(0L);
                        productUserEntity.setChildIds(JSON.toJSONString(childProductMap.get(productUserEntity.getDataId())));
                        parentAddProductUserList.add(productUserEntity);
                        for (Long childId : childProductMap.get(productUserEntity.getDataId())) {
                            userEntity = new ProductUserEntity();
                            userEntity.setParentId(productUserEntity.getDataId());
                            userEntity.setCorpid(productUserEntity.getCorpid());
                            userEntity.setUserName(productUserEntity.getUserName());
                            userEntity.setUserAvatar(productUserEntity.getUserAvatar());
                            userEntity.setRelationId(productUserEntity.getRelationId());
                            userEntity.setType(productUserEntity.getType());
                            userEntity.setDataId(childId);
                            childAddProductUserList.add(userEntity);
                        }
                    }
                }
            }
        }
        if (CollectionsUtil.isNotEmpty(childAddProductUserList)) {
            int insertTotal = childAddProductUserList.size();
            int insertPageSize = 1000;
            int insertTotalPage = (insertTotal % insertPageSize == 0) ? (insertTotal / insertPageSize) : (insertTotal / insertPageSize) + 1;
            for (int page = 0; page < insertTotalPage; page++) {
                List<ProductUserEntity> insertList;
                if (page == insertTotalPage - 1) {
                    insertList = childAddProductUserList.subList(insertPageSize * page, childAddProductUserList.size());
                } else {
                    insertList = childAddProductUserList.subList(insertPageSize * page, insertPageSize * (page + 1));
                }
                productUserModel.inserBatch(insertList);
            }
        }
        if (CollectionsUtil.isNotEmpty(parentAddProductUserList)) {
            int insertTotal = parentAddProductUserList.size();
            int insertPageSize = 1000;
            int insertTotalPage = (insertTotal % insertPageSize == 0) ? (insertTotal / insertPageSize) : (insertTotal / insertPageSize) + 1;
            for (int page = 0; page < insertTotalPage; page++) {
                List<ProductUserEntity> updateList;
                if (page == insertTotalPage - 1) {
                    updateList = parentAddProductUserList.subList(insertPageSize * page, parentAddProductUserList.size());
                } else {
                    updateList = parentAddProductUserList.subList(insertPageSize * page, insertPageSize * (page + 1));
                }
                productUserDao.updateBatchNotByCorpid(updateList);
            }
        }
        LOG.warn("consume:" + (DateTimeUtil.getInt() - start));
        LOG.warn("操作成功");
        return null;
    }

    @RequestMapping(value = "/fixProductAssociationUser", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String fixProductAssociationUser(@RequestBody @Valid FixDataJobDTO fixDataJobDTO, BindingResult br) throws Exception {
        if (!proBaseConfig.getXbbCode().equals(fixDataJobDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
        }
        long start = DateTimeUtil.getInt();
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(ParameterConstant.PARENT_ID, 0);
        param.put("orderBy", "id");
        param.put("pageSize", 1000);
        param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        param.put("childIdsIsNull", 1);
        param.put("addTimeEnd", fixDataJobDTO.getAddTime());
        List<ProductUserEntity> childAddProductUserList = new ArrayList<>();
        Set<Long> parentIdSet = new HashSet<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        boolean flag = true;
        while (flag) {
            List<ProductUserEntity> productUserEntityList = productUserModel.findEntitys(param);
            if (Objects.isNull(productUserEntityList) || productUserEntityList.isEmpty()) {
                flag = false;
            } else {
                LOG.warn("遍历id到" + productUserEntityList.get(productUserEntityList.size() - 1).getId());
                param.put("idGte", productUserEntityList.get(productUserEntityList.size() - 1).getId());
                for (ProductUserEntity productUserEntity : productUserEntityList) {
                    if (Objects.nonNull(productUserEntity.getDataId())) {
                        parentIdSet.add(productUserEntity.getDataId());
                    }
                }
                if (parentIdSet.isEmpty()) {
                    continue;
                }
                BoolQueryBuilder boolQueryBuilder = boolQuery();
                boolQueryBuilder.filter(termsQuery("data." + ProductEnum.PARENT_ID.getAttr(), parentIdSet));
                List<String> fieldList = new ArrayList<>();
                fieldList.add(StringConstant.SAAS_LINK_BUSINESS_ID);
                fieldList.add("data." + ProductEnum.PARENT_ID.getAttr());
                List<PaasFormDataEntity> childProductList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_PRODUCT, boolQueryBuilder, PaasFormDataEntity.class, fieldList);
                Map<Long, List<Long>> childProductMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                childProductList.forEach(child -> {
                    Long parentId = null;
                    if (Objects.nonNull(child.getData()) && Objects.nonNull(child.getData().getLong(ProductEnum.PARENT_ID.getAttr()))) {
                        parentId = child.getData().getLong(ProductEnum.PARENT_ID.getAttr());
                    }
                    if (Objects.nonNull(parentId)) {
                        List<Long> childIdList = childProductMap.getOrDefault(parentId, new ArrayList<>());
                        childIdList.add(child.getId());
                        childProductMap.put(parentId, childIdList);
                    }
                });
                ProductUserEntity userEntity;
                for (ProductUserEntity productUserEntity : productUserEntityList) {
                    if (CollectionsUtil.isNotEmpty(childProductMap.get(productUserEntity.getDataId()))) {
                        for (Long childId : childProductMap.get(productUserEntity.getDataId())) {
                            userEntity = new ProductUserEntity();
                            userEntity.setParentId(productUserEntity.getDataId());
                            userEntity.setCorpid(productUserEntity.getCorpid());
                            userEntity.setUserName(productUserEntity.getUserName());
                            userEntity.setUserAvatar(productUserEntity.getUserAvatar());
                            userEntity.setRelationId(productUserEntity.getRelationId());
                            userEntity.setType(productUserEntity.getType());
                            userEntity.setDataId(childId);
                            childAddProductUserList.add(userEntity);
                        }
                    }
                }
            }
        }
        if (CollectionsUtil.isNotEmpty(childAddProductUserList)) {
            int insertTotal = childAddProductUserList.size();
            int insertPageSize = 1000;
            int insertTotalPage = (insertTotal % insertPageSize == 0) ? (insertTotal / insertPageSize) : (insertTotal / insertPageSize) + 1;
            for (int page = 0; page < insertTotalPage; page++) {
                List<ProductUserEntity> insertList;
                if (page == insertTotalPage - 1) {
                    insertList = childAddProductUserList.subList(insertPageSize * page, childAddProductUserList.size());
                } else {
                    insertList = childAddProductUserList.subList(insertPageSize * page, insertPageSize * (page + 1));
                }
                productUserModel.inserBatch(insertList);
            }
        }
        LOG.warn("consume:" + (DateTimeUtil.getInt() - start));
        LOG.warn("操作成功");
        return null;
    }


    @RequestMapping(value = "/productAssociationUser", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String productAssociationUser(@RequestBody @Valid FixDataJobDTO fixDataJobDTO, BindingResult br) throws Exception {
        if (!proBaseConfig.getXbbCode().equals(fixDataJobDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
        }
        long start = DateTimeUtil.getInt();
        List<String> corpidList = fixDataJobDTO.getCorpidList();
        if (CollectionsUtil.isEmpty(corpidList)) {
            corpidList = productModel.getCorpidList();
        }
        LOG.warn("数据库中共有公司" + corpidList.size() + "家");
        int corpidCount = 0;
        for (String corpid : corpidList) {
            Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
            param.put(ParameterConstant.CORPID, corpid);
            Integer totalCount = productUserModel.getEntitysCount(param);
            LOG.warn("corpid:" + corpid + "数据库中共有产品团队" + totalCount + "条数据");
            int pageSize = 500;
            int totalPage = (totalCount % pageSize == 0) ? (totalCount / pageSize) : (totalCount / pageSize) + 1;
            int lastPageSize = (totalCount % pageSize == 0) ? pageSize : (totalCount % pageSize);
            List<ProductUserEntity> childProductUserList  = new ArrayList<>();
            Set<Long> parentIdSet = new HashSet<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            for (int page = 0; page < totalPage; page++) {
                if (page == totalPage - 1) {
                    param.put("pageNum", lastPageSize);
                } else {
                    param.put("pageNum", pageSize);
                }
                param.put("start", page * pageSize);
                LOG.warn("第" + (page+1) + "页开始");
                List<ProductUserEntity> productUserEntityList = productUserModel.findEntitys(param);
                if (productUserEntityList.isEmpty()) {
                    continue;
                }

               /* for (ProductUserEntity productUserEntity : productUserEntityList) {
                    parentIdIn.add(productUserEntity.getDataId());
                    parentIdSet.add(productUserEntity.getParentId() == null ? 0L : productUserEntity.getParentId());
                }
                BoolQueryBuilder boolQueryBuilder = boolQuery();
                boolQueryBuilder.filter(termQuery(ParameterConstant.CORPID + StringConstant.POINT + StringConstant.KEY_WORD, corpid));
                boolQueryBuilder.filter(termsQuery("data." + ProductEnum.PARENT_ID.getAttr(), parentIdIn));
                List<String> fieldList = new ArrayList<>();
                fieldList.add(StringConstant.SAAS_LINK_BUSINESS_ID);
                fieldList.add("data." + ProductEnum.PARENT_ID.getAttr());
                List<PaasFormDataEntity> childProductList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_PRODUCT, boolQueryBuilder, PaasFormDataEntity.class, fieldList);
                Map<Long, List<Long>> childProductMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                childProductList.forEach(child -> {
                    Long parentId = null;
                    if (Objects.nonNull(child.getData()) && Objects.nonNull(child.getData().getLong(ProductEnum.PARENT_ID.getAttr()))) {
                        parentId = child.getData().getLong(ProductEnum.PARENT_ID.getAttr());
                    }
                    if (Objects.nonNull(parentId)) {
                        List<Long> childIdList  = childProductMap.getOrDefault(parentId, new ArrayList<>());
                        childIdList.add(child.getId());
                        childProductMap.put(parentId, childIdList);
                    }
                });*/
                ProductUserEntity userEntity;
                for (ProductUserEntity productUserEntity : productUserEntityList) {
                    parentIdSet.add(productUserEntity.getParentId());
                    if (Objects.nonNull(productUserEntity.getChildIds())) {
                        List<Long> childProductIdList = JSON.parseArray(productUserEntity.getChildIds()).toJavaList(Long.class);
                        if (CollectionsUtil.isNotEmpty(childProductIdList)) {
                            for (Long childId : childProductIdList) {
                                userEntity = new ProductUserEntity();
                                userEntity.setParentId(productUserEntity.getDataId());
                                userEntity.setCorpid(productUserEntity.getCorpid());
                                userEntity.setUserName(productUserEntity.getUserName());
                                userEntity.setUserAvatar(productUserEntity.getUserAvatar());
                                userEntity.setRelationId(productUserEntity.getRelationId());
                                userEntity.setType(productUserEntity.getType());
                                userEntity.setDataId(childId);
                                childProductUserList.add(userEntity);
                            }
                        }
                    }
                }
                LOG.warn("第" + (page+1) + "页结束");
            }
            if (CollectionsUtil.isNotEmpty(childProductUserList) && parentIdSet.size() <= 1) {
                int insertTotal = childProductUserList.size();
                int insertPageSize = 500;
                int insertTotalPage = (insertTotal % insertPageSize == 0) ? (insertTotal / insertPageSize) : (insertTotal / insertPageSize) + 1;
                for (int page = 0; page < insertTotalPage; page++) {
                    List<ProductUserEntity> insertList;
                    if (page == insertTotalPage - 1) {
                        insertList = childProductUserList.subList(insertPageSize * page, childProductUserList.size());
                    } else {
                        insertList = childProductUserList.subList(insertPageSize * page, insertPageSize * (page + 1));
                    }
                    productUserModel.inserBatch(insertList);
                }
            }
            ++ corpidCount;
            LOG.warn("公司" + corpidCount + "/" + corpidList.size());
        }
        LOG.warn("consume:" + (DateTimeUtil.getInt() - start));
        LOG.warn("操作成功");
        return null;
    }


    @RequestMapping(value = "/addSupplierName", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String addSupplierName(@RequestBody @Valid FixDataJobDTO fixDataJobDTO, BindingResult br) throws Exception {
        if (!proBaseConfig.getXbbCode().equals(fixDataJobDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
        }
        List<String> corpidList = fixDataJobDTO.getCorpidList();
        if (CollectionsUtil.isEmpty(corpidList)) {
            corpidList = companyModel.getCorpidList();
        }
        LOG.warn("数据库中共有公司" + corpidList.size() + "家");
        Integer corpidCount = 0;
        for (String corpid : corpidList) {
            Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
            param.put(ParameterConstant.CORPID, corpid);
            Integer totalCount = supplierProductModel.getEntitysCount(param);
            LOG.warn("corpid:" + corpid + "数据库中共有产品供应商" + totalCount + "条数据");

            int pageSize = 500;
            int totalPage = (totalCount % pageSize == 0) ? (totalCount / pageSize) : (totalCount / pageSize) + 1;
            int lastPageSize = (totalCount % pageSize == 0) ? pageSize : (totalCount % pageSize);
            for (int page = 0; page < totalPage; page++) {
                List<SupplierProductEntity> childSupplierProductList  = new ArrayList<>();
                if (page == totalPage - 1) {
                    param.put("pageNum", lastPageSize);
                } else {
                    param.put("pageNum", pageSize);
                }
                param.put("start", page * pageSize);
                LOG.warn("第" + page + "页开始");
                List<SupplierProductEntity> supplierProductEntityList = supplierProductModel.findEntitys(param);
                if (supplierProductEntityList.isEmpty()) {
                    continue;
                }
                Set<Long> supplierIdIn = new HashSet<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                for (SupplierProductEntity supplierProductEntity : supplierProductEntityList) {
                    supplierIdIn.add(supplierProductEntity.getSupplierId());
                }
                BoolQueryBuilder boolQueryBuilder = boolQuery();
                boolQueryBuilder.filter(termQuery(ParameterConstant.CORPID + StringConstant.POINT + StringConstant.KEY_WORD, corpid));
                boolQueryBuilder.filter(termsQuery(StringConstant.SAAS_LINK_BUSINESS_ID, supplierIdIn));
                List<String> fieldList = new ArrayList<>();
                fieldList.add(StringConstant.SAAS_LINK_BUSINESS_ID);
                fieldList.add("data." + SupplierEnum.SUPPLIER_NAME.getAttr());
                List<PaasFormDataEntity> supplieList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_SUPPLIER, boolQueryBuilder, PaasFormDataEntity.class, fieldList);
                Map<Long, String> supplierNameMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                supplieList.forEach(supplier -> {
                    if (Objects.nonNull(supplier.getData()) ) {
                        supplierNameMap.put(supplier.getId(),
                                Objects.toString(supplier.getData().get(SupplierEnum.SUPPLIER_NAME.getAttr()), ""));
                    }
                });
                List<SupplierProductEntity> updateList = new ArrayList<>();
                for (SupplierProductEntity supplierProductEntity : supplierProductEntityList) {
                    supplierProductEntity.setSupplierName(supplierNameMap.getOrDefault(supplierProductEntity.getSupplierId(), ""));
                    updateList.add(supplierProductEntity);
                }
                supplierProductModel.updateBatch(updateList, corpid);
                LOG.warn("第" + page + "页结束");
            }
            ++ corpidCount;
            LOG.warn("公司" + corpidCount + "/" + corpidList.size());
        }
        LOG.warn("操作成功");
        return null;
    }

    @RequestMapping(value = "/addAllStockInfo", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String addAllStockInfo(@RequestBody @Valid FixDataJobDTO fixDataJobDTO, BindingResult br) throws Exception {
        if (!proBaseConfig.getXbbCode().equals(fixDataJobDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
        }
        List<String> corpidList = fixDataJobDTO.getCorpidList();
        if (CollectionsUtil.isEmpty(corpidList)) {
            corpidList = companyModel.getCorpidList();
        }
        LOG.warn("数据库中共有公司" + corpidList.size() + "家");
        int corpidCount = 0;
        for (String corpid : corpidList) {
            BoolQueryBuilder boolQueryBuilder = boolQuery();
            boolQueryBuilder.filter(termQuery(ParameterConstant.CORPID + StringConstant.POINT + StringConstant.KEY_WORD, corpid));
            boolQueryBuilder.filter(termQuery(ParameterConstant.DEL, DelEnum.NORMAL.getDel()));
            boolQueryBuilder.mustNot(termQuery(ProductEnum.getAttrConnectData(ProductEnum.PARENT_ID), 0));
            List<String> fieldList = new ArrayList<>();
            fieldList.add(FieldTypeEnum.DATAID.getAlias());
            fieldList.add(ProductEnum.getAttrConnectData(ProductEnum.ORI_STOCK));
            fieldList.add(ProductEnum.getAttrConnectData(ProductEnum.STOCK_UPPER_LIMIT));
            fieldList.add(ProductEnum.getAttrConnectData(ProductEnum.STOCK_LOWER_LIMIT));
            fieldList.add(ProductEnum.getAttrConnectData(ProductEnum.COST));
            fieldList.add(ProductEnum.getAttrConnectData(ProductEnum.PARENT_ID));
            fieldList.add(ProductEnum.getAttrConnectData(ProductEnum.IS_NOTIFY));
            List<PaasFormDataEntity> productList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_PRODUCT, boolQueryBuilder, PaasFormDataEntity.class, fieldList);
            int totalCount = productList.size();
            LOG.warn("该公司" + corpid +"在es中共有" + totalCount + "条数据");
            List<Long> productIdList = new ArrayList<>();
            Map<Long, PaasFormDataEntity> productMap = new HashMap<>(productList.size());
            productList.forEach(item -> {
                productIdList.add(item.getDataId());
                productMap.put(item.getDataId(), item);
            });
            int pageSize = 500;
            int totalPage = (totalCount % pageSize == 0) ? (totalCount / pageSize) : (totalCount / pageSize) + 1;
            int lastPageSize = (totalCount % pageSize == 0) ? pageSize : (totalCount % pageSize);
            Integer insertCount = 0;
            for (int page = 0; page < totalPage; page++) {
                int start = page * pageSize;
                int end;
                if (page == totalPage - 1) {
                    end = start + lastPageSize;
                } else {
                    end = start + pageSize;
                }
                List<Long> pageProductIdList = new ArrayList<>(productIdList.subList(start, end));
                LOG.warn("第" + page + "页开始");
                Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
                param.put(ParameterConstant.CORPID, corpid);
                param.put("productIdIn", pageProductIdList);
                param.put("warehouseChecked", 1);
                List<ProductWarehouseEntity> productWarehouseList = productWarehouseModel.findEntitysWithWarehouseChecked(param,1);
                if (productWarehouseList.isEmpty()) {
                    continue;
                }
                Set<Long> haveAllWarehouse = new HashSet<>();
                Iterator<ProductWarehouseEntity> iterator = productWarehouseList.iterator();
                while (iterator.hasNext()) {
                    ProductWarehouseEntity productWarehouseEntity = iterator.next();
                    if (Objects.equals(productWarehouseEntity.getWarehouseId(), 0L)) {
                        haveAllWarehouse.add(productWarehouseEntity.getProductId());
                        iterator.remove();
                    }
                }
                Map<Long, Double> productNumMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                for (ProductWarehouseEntity item : productWarehouseList) {
                    Long productId = item.getProductId();
                    if (haveAllWarehouse.contains(productId)) {
                        continue;
                    }
                    Double num = Objects.isNull(item.getNum()) ? 0D : item.getNum();
                    if (productNumMap.containsKey(productId)) {
                        productNumMap.put(productId, productNumMap.get(productId) + num);
                    } else {
                        productNumMap.put(productId, num);
                    }
                }
                List<ProductWarehouseEntity> insertList = new ArrayList<>(productNumMap.size());
                productNumMap.forEach((key, value) -> {
                    if (productMap.containsKey(key) && Objects.equals(productMap.get(key).getData().getInteger(ProductEnum.IS_NOTIFY.getAttr()), 1)) {
                        PaasFormDataEntity paasFormDataEntity = productMap.get(key);
                        ProductWarehouseEntity productWarehouseEntity = new ProductWarehouseEntity();
                        productWarehouseEntity.setCorpid(corpid);
                        productWarehouseEntity.setWarehouseId(0L);
                        productWarehouseEntity.setWarehouseName("全部仓库");
                        productWarehouseEntity.setProductId(key);
                        productWarehouseEntity.setParentId(paasFormDataEntity.getData().getLong(ProductEnum.PARENT_ID.getAttr()));
                        productWarehouseEntity.setNum(value);
                        productWarehouseEntity.setOriNum(paasFormDataEntity.getData().getDouble(ProductEnum.ORI_STOCK.getAttr()));
                        productWarehouseEntity.setIsNotify(paasFormDataEntity.getData().getInteger(ProductEnum.IS_NOTIFY.getAttr()));
                        Double stockLowerLimit = Objects.isNull(paasFormDataEntity.getData().getDouble(ProductEnum.STOCK_LOWER_LIMIT.getAttr())) ? 0D : paasFormDataEntity.getData().getDouble(ProductEnum.STOCK_LOWER_LIMIT.getAttr());
                        productWarehouseEntity.setStockLowerLimit(stockLowerLimit);
                        Double stockUpperLimit = Objects.isNull(paasFormDataEntity.getData().getDouble(ProductEnum.STOCK_UPPER_LIMIT.getAttr())) ? 0D : paasFormDataEntity.getData().getDouble(ProductEnum.STOCK_UPPER_LIMIT.getAttr());
                        productWarehouseEntity.setStockUpperLimit(stockUpperLimit);
                        productWarehouseEntity.setCost(paasFormDataEntity.getData().getDouble(ProductEnum.COST.getAttr()));
                        productWarehouseEntity.setTotalCost(Arith.mul(productWarehouseEntity.getNum(),productWarehouseEntity.getCost()));
                        productWarehouseEntity.setWarehouseChecked(1);
                        productWarehouseEntity.setWarehouseKey(productWarehouseEntity.getProductId() + "_" + productWarehouseEntity.getWarehouseId());
                        insertList.add(productWarehouseEntity);
                    }
                });
                if (!insertList.isEmpty()) {
                    productWarehouseModel.insertBatch(insertList);
                    insertCount += insertList.size();
                }
                LOG.warn("第" + page + "页结束");
            }
            LOG.warn("共插入" + insertCount + "条全仓数据");
            ++ corpidCount;
            LOG.warn("公司" + corpidCount + "/" + corpidList.size());
        }
        LOG.warn("操作成功");
        return null;
    }

    @RequestMapping(value = "/addStockInfoToProduct", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String addStockInfoToProduct(@RequestBody @Valid FixDataJobDTO fixDataJobDTO, BindingResult br) throws Exception {
        if (!proBaseConfig.getXbbCode().equals(fixDataJobDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
        }
        long startTime = DateTimeUtil.getInt();
        List<String> corpidList = fixDataJobDTO.getCorpidList();
        if (CollectionsUtil.isEmpty(corpidList)) {
            corpidList = productModel.getCorpidList();
        }
        LOG.warn("数据库中共有公司" + corpidList.size() + "家");
        int corpidCount = 0;
        for (String corpid : corpidList) {
            BoolQueryBuilder boolQueryBuilder = boolQuery();
            boolQueryBuilder.filter(termQuery(ParameterConstant.CORPID + StringConstant.POINT + StringConstant.KEY_WORD, corpid));
            boolQueryBuilder.filter(termQuery(ParameterConstant.DEL, DelEnum.NORMAL.getDel()));
            boolQueryBuilder.mustNot(termQuery(ProductEnum.getAttrConnectData(ProductEnum.PARENT_ID), 0));
            List<String> fieldList = new ArrayList<>();
            fieldList.add(FieldTypeEnum.DATAID.getAlias());
            fieldList.add(ProductEnum.getAttrConnectData(ProductEnum.WAREHOUSE));
            fieldList.add(ProductEnum.getAttrConnectData(ProductEnum.ORI_STOCK));
            fieldList.add(ProductEnum.getAttrConnectData(ProductEnum.STOCK_UPPER_LIMIT));
            fieldList.add(ProductEnum.getAttrConnectData(ProductEnum.STOCK_LOWER_LIMIT));
            fieldList.add(ProductEnum.getAttrConnectData(ProductEnum.COST));
            fieldList.add(ProductEnum.getAttrConnectData(ProductEnum.PARENT_ID));
            fieldList.add(ProductEnum.getAttrConnectData(ProductEnum.IS_NOTIFY));
            List<PaasFormDataEntity> productList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_PRODUCT, boolQueryBuilder, PaasFormDataEntity.class, fieldList);
            int totalCount = productList.size();
            LOG.warn("该公司" + corpid +"在es中共有" + totalCount + "条数据");
            List<Long> productIdList = new ArrayList<>();
            Map<Long, PaasFormDataEntity> productMap = new HashMap<>(productList.size());
            productList.forEach(item -> {
                productIdList.add(item.getDataId());
                productMap.put(item.getDataId(), item);
            });
            int pageSize = 500;
            int totalPage = (totalCount % pageSize == 0) ? (totalCount / pageSize) : (totalCount / pageSize) + 1;
            int lastPageSize = (totalCount % pageSize == 0) ? pageSize : (totalCount % pageSize);
            Integer updateCount = 0;
            Integer insertCount = 0;
            for (int page = 0; page < totalPage; page++) {
                int start = page * pageSize;
                int end;
                if (page == totalPage - 1) {
                    end = start + lastPageSize;
                } else {
                    end = start + pageSize;
                }
                List<Long> pageProductIdList = new ArrayList<>(productIdList.subList(start, end));
                LOG.warn("第" + page + "页开始");
                Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
                param.put(ParameterConstant.CORPID, corpid);
                param.put("warehouseChecked", 1);
                param.put("productIdIn", pageProductIdList);
                List<ProductWarehouseEntity> productWarehouseList = productWarehouseModel.findEntitysWithWarehouseChecked(param,1);
                if (productWarehouseList.isEmpty()) {
                    continue;
                }
                Map<Long, Set<Long>> warehouseIdMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                productWarehouseList.forEach(item -> {
                    Long productId = item.getProductId();
                    Long warehouseId = item.getWarehouseId();
                    if (Objects.nonNull(warehouseId) && !Objects.equals(warehouseId, 0L)) {
                        if (warehouseIdMap.containsKey(productId)) {
                            warehouseIdMap.get(productId).add(warehouseId);
                        } else {
                            Set<Long> warehouseSet = new HashSet<>();
                            warehouseSet.add(warehouseId);
                            warehouseIdMap.put(productId, warehouseSet);
                        }
                    }

                });
                List<UpdateDataEntity> updateList = new ArrayList<>();
                warehouseIdMap.forEach((key, value) -> {
                    JSONObject data = new JSONObject();
                    data.put(ProductEnum.WAREHOUSE.getAttr(), JSON.parseArray(JSON.toJSONString(value)));
                    updateList.add(ExplainUtil.getUpdateData(key,data,corpid));
                });

                // 全仓数据
                Set<Long> haveAllWarehouse = new HashSet<>();
                Iterator<ProductWarehouseEntity> iterator = productWarehouseList.iterator();
                while (iterator.hasNext()) {
                    ProductWarehouseEntity productWarehouseEntity = iterator.next();
                    if (Objects.equals(productWarehouseEntity.getWarehouseId(), 0L)) {
                        haveAllWarehouse.add(productWarehouseEntity.getProductId());
                        iterator.remove();
                    }
                }
                Map<Long, Double> productNumMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                for (ProductWarehouseEntity item : productWarehouseList) {
                    Long productId = item.getProductId();
                    if (haveAllWarehouse.contains(productId)) {
                        continue;
                    }
                    Double num = Objects.isNull(item.getNum()) ? 0D : item.getNum();
                    if (productNumMap.containsKey(productId)) {
                        productNumMap.put(productId, Arith.add(productNumMap.get(productId), num));
                    } else {
                        productNumMap.put(productId, num);
                    }
                }
                List<ProductWarehouseEntity> insertList = new ArrayList<>(productNumMap.size());
                productNumMap.forEach((key, value) -> {
                    if (productMap.containsKey(key) && Objects.equals(productMap.get(key).getData().getInteger(ProductEnum.IS_NOTIFY.getAttr()), 1)) {
                        PaasFormDataEntity paasFormDataEntity = productMap.get(key);
                        ProductWarehouseEntity productWarehouseEntity = new ProductWarehouseEntity();
                        productWarehouseEntity.setCorpid(corpid);
                        productWarehouseEntity.setWarehouseId(0L);
                        productWarehouseEntity.setWarehouseName("全部仓库");
                        productWarehouseEntity.setProductId(key);
                        productWarehouseEntity.setParentId(paasFormDataEntity.getData().getLong(ProductEnum.PARENT_ID.getAttr()));
                        productWarehouseEntity.setNum(value);
                        productWarehouseEntity.setOriNum(paasFormDataEntity.getData().getDouble(ProductEnum.ORI_STOCK.getAttr()));
                        productWarehouseEntity.setIsNotify(paasFormDataEntity.getData().getInteger(ProductEnum.IS_NOTIFY.getAttr()));
                        Double stockLowerLimit = Objects.isNull(paasFormDataEntity.getData().getDouble(ProductEnum.STOCK_LOWER_LIMIT.getAttr())) ? 0D : paasFormDataEntity.getData().getDouble(ProductEnum.STOCK_LOWER_LIMIT.getAttr());
                        productWarehouseEntity.setStockLowerLimit(stockLowerLimit);
                        Double stockUpperLimit = Objects.isNull(paasFormDataEntity.getData().getDouble(ProductEnum.STOCK_UPPER_LIMIT.getAttr())) ? 0D : paasFormDataEntity.getData().getDouble(ProductEnum.STOCK_UPPER_LIMIT.getAttr());
                        productWarehouseEntity.setStockUpperLimit(stockUpperLimit);
                        productWarehouseEntity.setCost(paasFormDataEntity.getData().getDouble(ProductEnum.COST.getAttr()));
                        productWarehouseEntity.setTotalCost(Arith.mul(productWarehouseEntity.getNum(),productWarehouseEntity.getCost()));
                        productWarehouseEntity.setWarehouseChecked(1);
                        productWarehouseEntity.setWarehouseKey(productWarehouseEntity.getProductId() + "_" + productWarehouseEntity.getWarehouseId());
                        insertList.add(productWarehouseEntity);
                    }
                });
                if (!insertList.isEmpty()) {
                    productWarehouseModel.insertBatch(insertList);
                    insertCount += insertList.size();
                }
                if (!updateList.isEmpty()) {
                    if (Objects.equals(fixDataJobDTO.getIsNeedUpdateEs(), 1)) {
                        productModel.updateBatch(updateList, corpid, WriteRequest.RefreshPolicy.NONE);
                    } else {
                        productModel.updateBatch4JobNoEs(updateList, corpid);
                    }

                    updateCount += updateList.size();
                }
                LOG.warn("第" + page + "页结束");
            }
            LOG.warn("共插入" + insertCount + "条全仓数据");
            LOG.warn("共更新" + updateCount + "条产品数据");
            ++ corpidCount;
            LOG.warn("公司" + corpidCount + "/" + corpidList.size());
        }
        LOG.warn("consume:" + (DateTimeUtil.getInt() - startTime));
        LOG.warn("操作成功");
        return null;
    }

    /**
    * @Description:  更新当前数据库所有的仓库的期初状态
    * @Param: [fixDataJobDTO, br]
    * @return: java.lang.String
    * @Author: cyy
    * @Date: 2019/11/11
    */
    @RequestMapping(value = "/updateWarehouseOriStock", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String updateWarehouseOriStock(@RequestBody @Valid FixDataJobDTO fixDataJobDTO, BindingResult br) throws Exception {
        if (!proBaseConfig.getXbbCode().equals(fixDataJobDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
        }
        List<String> corpidList = fixDataJobDTO.getCorpidList();
        if (CollectionsUtil.isEmpty(corpidList)) {
            corpidList = companyModel.getCorpidList();
        }
        Integer index = 1;
        for (String corpid : corpidList) {
            LOG.warn(index + "/" + corpidList.size());
            index ++;
            BoolQueryBuilder boolQueryBuilder = boolQuery();
            boolQueryBuilder.filter(termQuery(ParameterConstant.CORPID + StringConstant.POINT + StringConstant.KEY_WORD, corpid));
            boolQueryBuilder.filter(termQuery(ParameterConstant.DEL, DelEnum.NORMAL.getDel()));
            List<PaasFormDataEntity> warehouseEntityExtList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_WAREHOUSE, boolQueryBuilder, PaasFormDataEntity.class, null);
            if (warehouseEntityExtList.isEmpty()) {
                continue;
            }
            LOG.warn("updateWarehouseOriStock更新仓库数据" + warehouseEntityExtList.size() + "条");
            List<UpdateDataEntity> updateWarehouseList = new ArrayList<>();
            for (PaasFormDataEntity warehouseEntityExt : warehouseEntityExtList) {
                JSONObject warehouseData = new JSONObject();
                warehouseData.put(WarehouseEnum.ORI_STOCK.getAttr(), WarehouseOriStockEnum.NO_NEED.getCode());
                updateWarehouseList.add(ExplainUtil.getUpdateData(warehouseEntityExt.getId(),warehouseData,corpid));
            }
            warehouseModel.updateBatch(updateWarehouseList,corpid);

        }
        LOG.warn("操作成功");
        return null;
    }

    /**
     * @Description: 用于将已有老数据的产品编号值刷到外面
     * @Param: [stockDTO, br]
     * @return: java.lang.String
     * @Author: cyy
     * @Date: 2019/8/27
     */
    @RequestMapping(value = "/productNoAndSku", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String initProductNoAndSku(@RequestBody @Valid ProductDTO productDTO, BindingResult br) throws Exception {
        if (!proBaseConfig.getXbbCode().equals(productDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
        }
        List<String> corpidList = productDTO.getCorpidList();
        if (CollectionsUtil.isEmpty(corpidList)) {
            corpidList = companyModel.getCorpidList();
        }
        LOG.warn("数据库中共有公司" + corpidList.size() + "家");
        Integer index = 1;
        for (String corpid : corpidList) {
            LOG.warn(index + "/" + corpidList.size());
            index ++;
            BoolQueryBuilder boolQueryBuilder = boolQuery();
            boolQueryBuilder.filter(termQuery(ParameterConstant.CORPID + StringConstant.POINT + StringConstant.KEY_WORD, corpid));
            boolQueryBuilder.filter(termQuery(ParameterConstant.DEL, DelEnum.NORMAL.getDel()));
            boolQueryBuilder.filter(termQuery(ProductEnum.getAttrConnectData(ProductEnum.PARENT_ID), 0));
            boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD,IndexTypeEnum.IDX_SAAS_PRODUCT.getType()));
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            sourceBuilder.query(boolQueryBuilder);
            SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_PRODUCT.getIndex());
            searchRequest.source(sourceBuilder);
            Long totalCountLong = xbbElasticsearchRestTemplate.count(searchRequest, PaasFormDataEntityExt.class);
            Integer totalCount = Objects.isNull(totalCountLong) ? 0 : totalCountLong.intValue();
            LOG.warn("corpid:" + corpid + "数据库中共有父产品" + totalCount + "条数据");
            int pageSize = 500;
            int totalPage = (totalCount % pageSize == 0) ? (totalCount / pageSize) : (totalCount / pageSize) + 1;
            for (int page = 0; page < totalPage; page++) {
                //设置分页
                PageRequest pageRequest = EsUtil.setPage(sourceBuilder, page, pageSize);
                XbbAggregatedPage<PaasFormDataEntityExt> esEntities = xbbElasticsearchRestTemplate.queryForPages(pageRequest,searchRequest, PaasFormDataEntityExt.class);
                if (esEntities == null) {
                    LOG.warn("corpid:" + corpid + "查询es服务器没有查到任何数据");
                }
                List<PaasFormDataEntity> productEntityExtList = new ArrayList<>(esEntities.getContent());
                if (productEntityExtList.isEmpty()) {
                    continue;
                }
                List<Long> productIdList = new ArrayList<>();
                productEntityExtList.forEach(item -> {
                    productIdList.add(item.getId());
                });
                boolQueryBuilder = boolQuery();
                boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
                boolQueryBuilder.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
                boolQueryBuilder.filter(termsQuery(ProductEnum.getAttrConnectData(ProductEnum.PARENT_ID), productIdList));
                List<String> fieldList = new ArrayList<>();
                fieldList.add(StringConstant.DATA_ID);
                fieldList.add(ProductEnum.getAttrConnectData(ProductEnum.PARENT_ID));
                List<ProductEntityExt> childProductList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_PRODUCT, boolQueryBuilder, ProductEntityExt.class, fieldList);
                Map<Long, List<Long>> childProductMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                childProductList.forEach(child -> {
                    Long parentId = null;
                    if (Objects.nonNull(child.getData()) && Objects.nonNull(child.getData().getLong(ProductEnum.PARENT_ID.getAttr()))) {
                        parentId = child.getData().getLong(ProductEnum.PARENT_ID.getAttr());
                    }
                    if (Objects.nonNull(parentId)) {
                        List<Long> childIdList  = childProductMap.getOrDefault(parentId, new ArrayList<>());
                        childIdList.add(child.getDataId());
                        childProductMap.put(parentId, childIdList);
                    }
                });
                List<UpdateDataEntity> updateDataEntityList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                productEntityExtList.forEach(item -> {
                    UpdateDataEntity updateDataEntity = new UpdateDataEntity();
                    updateDataEntity.setCorpid(corpid);
                    updateDataEntity.setId(item.getDataId());
                    updateDataEntity.setDel(DelEnum.NORMAL.getDel());
                    if (StringUtil.isEmpty(item.getSerialNo())){
                        // 老数据
                        updateDataEntity.setSerialNo(item.getData().getString(ProductEnum.PRODUCT_NO.getAttr()) == null ? "" : item.getData().getString(ProductEnum.PRODUCT_NO.getAttr()));
                    } else {
                        // 新数据
                        updateDataEntity.setSerialNo(item.getSerialNo());
                    }
                    updateDataEntityList.add(updateDataEntity);
                    List<Long> childIdList = childProductMap.get(item.getId());
                    if (Objects.nonNull(childIdList)) {
                        childIdList.forEach(child -> {
                            UpdateDataEntity childData = new UpdateDataEntity();
                            childData.setCorpid(corpid);
                            childData.setId(child);
                            childData.setDel(DelEnum.NORMAL.getDel());
                            if (StringUtil.isEmpty(item.getSerialNo())){
                                // 老数据
                                childData.setSerialNo(item.getData().getString(ProductEnum.PRODUCT_NO.getAttr()) == null ? "" : item.getData().getString(ProductEnum.PRODUCT_NO.getAttr()));
                            } else {
                                // 新数据
                                childData.setSerialNo(item.getSerialNo());
                            }
                            updateDataEntityList.add(childData);
                        });
                    }
                });
                if (CollectionsUtil.isNotEmpty(updateDataEntityList)) {
                    productModel.updateBatchSerialNo(updateDataEntityList);
                }
                List<UpdateDataEntity> updateProductList = new ArrayList<>();
                for (PaasFormDataEntity product : productEntityExtList) {
                    JSONObject productData = new JSONObject();
                    productData.put(ProductEnum.ENABLE_SKU.getAttr(), 1);
                    updateProductList.add(ExplainUtil.getUpdateData(product.getId(),productData,corpid));
                    List<Long> childIdList = childProductMap.get(product.getId());
                    if (Objects.nonNull(childIdList)) {
                        childIdList.forEach(child -> {
                            JSONObject childData = new JSONObject();
                            childData.put(ProductEnum.ENABLE_SKU.getAttr(), 1);
                            updateProductList.add(ExplainUtil.getUpdateData(child,childData,corpid));
                        });
                    }
                }
                if (CollectionsUtil.isNotEmpty(updateDataEntityList)) {
                    productModel.updateBatch(updateProductList,corpid);
                }
                LOG.warn("corpid:" + corpid + "数据库中共有父产品" + totalCount + "条数据" + "总共有" + totalPage + "页" + "已更新至第" + page + 1 + "页");
            }

        }
        return null;
    }

    /**
     * 暂时刷解释
     *
     * @param allScriptDTO
     * @param br
     * @return
     */
    @RequestMapping(value = "/fixStockForm", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String fixStockForm(@RequestBody @Valid AllScriptDTO allScriptDTO, BindingResult br) {
        XbbResponse<FormExplainAddBatchVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                FormExplainAddBatchVO formExplainAddBatchVO = repairExplainService.fixStockForm(allScriptDTO);
                response = new XbbResponse<>(formExplainAddBatchVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }

    @RequestMapping(value = "/fixStockFormData", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String fixStockFormData(@RequestBody @Valid FixOldStockExplainDTO fixOldStockExplainDTO, BindingResult br) throws Exception{
        if (!proBaseConfig.getXbbCode().equals(fixOldStockExplainDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
        }
        long start = DateTimeUtil.getInt();
        List<String> corpidList = fixOldStockExplainDTO.getCorpidList();
        if (CollectionsUtil.isEmpty(corpidList)) {
            corpidList = companyModel.getJxcCorpidList();
        }
        LOG.warn("数据库中共有jxc公司" + corpidList.size() + "家");
        Integer index = 1;
        for (String corpid : corpidList) {
            LOG.warn(index + "/" + corpidList.size());
            index ++;
            BoolQueryBuilder boolQueryBuilder = boolQuery();
            boolQueryBuilder.filter(termQuery(ParameterConstant.CORPID + StringConstant.POINT + StringConstant.KEY_WORD, corpid));
            boolQueryBuilder.filter(termQuery(ParameterConstant.DEL, DelEnum.NORMAL.getDel()));
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            SearchRequest searchRequest= null;
            if (Objects.equals(fixOldStockExplainDTO.getStockType(), 1)) {
                boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD,IndexTypeEnum.IDX_SAAS_INSTOCK.getType()));
                searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_INSTOCK.getIndex());
            }
            if (Objects.equals(fixOldStockExplainDTO.getStockType(), 2)) {
                boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD,IndexTypeEnum.IDX_SAAS_OUTSTOCK.getType()));
                searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_OUTSTOCK.getIndex());
            }
            sourceBuilder.query(boolQueryBuilder);
            searchRequest.source(sourceBuilder);
            Long totalCountLong = xbbElasticsearchRestTemplate.count(searchRequest, PaasFormDataEntityExt.class);
            Integer totalCount = Objects.isNull(totalCountLong) ? 0 : totalCountLong.intValue();
            LOG.warn("corpid:" + corpid + "es中有" + totalCount + "条数据");
            int pageSize = 1000;
            int totalPage = (totalCount % pageSize == 0) ? (totalCount / pageSize) : (totalCount / pageSize) + 1;
            Map<Integer, UpdateStockDataEntity> typeMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            List<PaasFormExplainEntity> explainList = paasFormExplainModel.getListForUpdateProduct(corpid, StockConstant.STOCK_TYPE_LIST);
            for (PaasFormExplainEntity paasFormExplainEntity : explainList) {
                UpdateStockDataEntity updateStockDataEntity = new UpdateStockDataEntity();
                updateStockDataEntity.setAppId(paasFormExplainEntity.getAppId());
                updateStockDataEntity.setMenuId(paasFormExplainEntity.getMenuId());
                updateStockDataEntity.setFormId(paasFormExplainEntity.getFormId());
                typeMap.put(paasFormExplainEntity.getBusinessType(), updateStockDataEntity);
            }
            for (int page = 0; page < totalPage; page++) {
                //设置分页
                PageRequest pageRequest = EsUtil.setPage(sourceBuilder, page, pageSize);
                XbbAggregatedPage<PaasFormDataEntityExt> esEntities = xbbElasticsearchRestTemplate.queryForPages(pageRequest,searchRequest, PaasFormDataEntityExt.class);
                if (esEntities == null) {
                    LOG.warn("corpid:" + corpid + "查询es服务器没有查到任何数据");
                }
                List<PaasFormDataEntity> instockEntityExtList = new ArrayList<>(esEntities.getContent());
                if (instockEntityExtList.isEmpty()) {
                    continue;
                }
                List<UpdateStockDataEntity> updateList = new ArrayList<>();
                for (PaasFormDataEntity entity : instockEntityExtList) {
                    Integer stockBusinessType = null;
                    if (Objects.equals(fixOldStockExplainDTO.getStockType(), 1)) {
                        Integer type = entity.getData().getInteger(InstockEnum.TYPE.getAttr());
                        InstockTypeEnum instockTypeEnum  = InstockTypeEnum.getByCode(type) == InstockTypeEnum.UNKNOWN
                                ? InstockTypeEnum.OTHER_INSTOCK : InstockTypeEnum.getByCode(type);
                        stockBusinessType = instockTypeEnum.getStockBusinessType();
                        if (Objects.equals("ding18b527cbc48f835535c2f4657eb6378f",corpid)){
                            LOG.warn("fixStockFormData" + fixOldStockExplainDTO.getStockType() +
                                    ",id:" + entity.getId() + ",type:" + type + ",stockBusinessType:" + stockBusinessType);
                        }
                    }
                    if (Objects.equals(fixOldStockExplainDTO.getStockType(), 2)) {
                        Integer type = entity.getData().getInteger(OutstockEnum.TYPE.getAttr());
                        OutstockTypeEnum outstockTypeEnum = OutstockTypeEnum.getByCode(type) == OutstockTypeEnum.UNKNOWN
                                ? OutstockTypeEnum.OTHER_OUTSTOCK : OutstockTypeEnum.getByCode(type);
                        stockBusinessType = outstockTypeEnum.getStockBusinessType();
                    }

                    UpdateStockDataEntity templateData = typeMap.get(stockBusinessType);
                    UpdateStockDataEntity updateStockDataEntity = new UpdateStockDataEntity();
                    updateStockDataEntity.setId(entity.getId());
                    updateStockDataEntity.setCorpid(entity.getCorpid());
                    updateStockDataEntity.setAppId(templateData.getAppId());
                    updateStockDataEntity.setMenuId(templateData.getMenuId());
                    updateStockDataEntity.setFormId(templateData.getFormId());
                    updateList.add(updateStockDataEntity);
                }
                if (CollectionsUtil.isNotEmpty(updateList)) {
                    if (Objects.equals("ding18b527cbc48f835535c2f4657eb6378f",corpid)){
                        LOG.warn("fixStockFormData" + fixOldStockExplainDTO.getStockType() + ":" + JSONArray.toJSONString(updateList));
                    }
                    if (Objects.equals(fixOldStockExplainDTO.getStockType(), 1)) {
                        instockModel.updateBatchDataByType(updateList, corpid);
                    }
                    if (Objects.equals(fixOldStockExplainDTO.getStockType(), 2)) {
                        outstockModel.updateBatchDataByType(updateList, corpid);
                    }
                }
                LOG.warn("corpid:" + corpid + "有" + totalCount + "条数据" + "总共有" + totalPage + "页" + "已更新至第" + (page + 1) + "页");
            }
        }
        LOG.warn("consume:" + (DateTimeUtil.getInt() - start));
        return "success";
    }
    /**
     * 先查所有退货入库单-->入库单产品-->红冲合同-->红冲合同产品--建立ref关系
     * @param fixDataJobDTO
     * @param br
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/addRefProductIdToRefundInstock", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String addRefProductIdToRefundInstock(@RequestBody @Valid FixDataJobDTO fixDataJobDTO, BindingResult br) throws Exception {
        if (!proBaseConfig.getXbbCode().equals(fixDataJobDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
        }
        long start = DateTimeUtil.getInt();
        List<String> corpidList = fixDataJobDTO.getCorpidList();
        if (CollectionsUtil.isEmpty(corpidList)) {
            corpidList = companyModel.getCorpidList();
        }
        LOG.warn("数据库中共有公司" + corpidList.size() + "家");
        int corpidCount = 0;
        for (String corpid : corpidList) {
            BoolQueryBuilder boolQueryBuilder = boolQuery();
            boolQueryBuilder.filter(termQuery(ParameterConstant.CORPID + StringConstant.POINT + StringConstant.KEY_WORD, corpid));
            boolQueryBuilder.filter(termQuery(ParameterConstant.DEL, DelEnum.NORMAL.getDel()));
            boolQueryBuilder.filter(termQuery(InstockEnum.getAttrConnectData(InstockEnum.TYPE), InstockTypeEnum.RED_CONTRACT_INSTOCK.getCode()));
            List<String> fieldList = new ArrayList<>();
            fieldList.add(FieldTypeEnum.DATAID.getAlias());
            fieldList.add(InstockEnum.getAttrConnectData(InstockEnum.REF_ID));
            List<PaasFormDataEntity> instockList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_INSTOCK, boolQueryBuilder, PaasFormDataEntity.class, fieldList);
            int totalCount = instockList.size();
            LOG.warn("该公司" + corpid +"在es中共有" + totalCount + "条数据");
            List<Long> instockIdList = new ArrayList<>();
            List<Long> refundIdList = new ArrayList<>();
            Map<Long, Long> refundInstockMap = new HashMap<>(instockList.size());
            instockList.forEach(item -> {
                if (Objects.nonNull(item.getData()) && Objects.nonNull(item.getData().getLong(InstockEnum.REF_ID.getAttr()))) {
                    instockIdList.add(item.getDataId());
                    Long refId = item.getData().getLong(InstockEnum.REF_ID.getAttr());
                    refundIdList.add(refId);
                    refundInstockMap.put(refId, item.getDataId());
                }
            });
            if (refundIdList.isEmpty()) {
                continue;
            }
            boolQueryBuilder = boolQuery();
            boolQueryBuilder.filter(termQuery(ParameterConstant.CORPID + StringConstant.POINT + StringConstant.KEY_WORD, corpid));
            boolQueryBuilder.filter(termQuery(ParameterConstant.DEL, DelEnum.NORMAL.getDel()));
            boolQueryBuilder.filter(termsQuery(FieldTypeEnum.DATAID.getAlias(), refundIdList));
            fieldList.clear();
            fieldList.add(FieldTypeEnum.DATAID.getAlias());
            fieldList.add(RefundEnum.getAttrConnectData(RefundEnum.RED_CONTRACT_ID));
            List<PaasFormDataEntity> refundList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_REFUND, boolQueryBuilder, PaasFormDataEntity.class, fieldList);
            Map<Long, Long> instockRedContractMap = new HashMap<>(instockList.size());
            List<Long> redContractIdList = new ArrayList<>();
            refundList.forEach(item -> {
                if (refundInstockMap.containsKey(item.getDataId())) {
                    Long refContractId = item.getData().getLong(RefundEnum.RED_CONTRACT_ID.getAttr());
                    instockRedContractMap.put(refundInstockMap.get(item.getDataId()), refContractId);
                    redContractIdList.add(refContractId);
                }
            });
            List<InstockProductEntity> instockProductEntities = instockProductModel.getProductsByInstockIdIn(corpid, instockIdList);
            List<ContractProductEntity> contractProductEntities = contractProductModel.getContractProductByContractIdIn(corpid, redContractIdList);
            Map<Long, List<InstockProductEntity>> instockProductMap = new HashMap<>(instockProductEntities.size());
            instockProductEntities.forEach(item -> {
                if (Objects.isNull(item.getRefProductId())) {
                    Long key = item.getIntoWarehouseId();
                    if (instockProductMap.containsKey(key)) {
                        instockProductMap.get(key).add(item);
                    } else {
                        List<InstockProductEntity> list = new ArrayList<>();
                        list.add(item);
                        instockProductMap.put(key,list);
                    }
                }
            });
            Map<Long, Map<Long, Long>> refContractProductMap = new HashMap<>(contractProductEntities.size());
            Map<Long, ContractProductEntity> contractProductMap = new HashMap<>(contractProductEntities.size());
            contractProductEntities.forEach(item -> {
                Long key = item.getContractId();
                if (refContractProductMap.containsKey(key)) {
                    refContractProductMap.get(key).put(item.getProductId(), item.getId());
                } else {
                    Map<Long, Long> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    map.put(item.getProductId(), item.getId());
                    refContractProductMap.put(key,map);
                }
                contractProductMap.put(item.getId(), item);
            });
            List<InstockProductEntity> instockUpdateList = new ArrayList<>();
            List<ContractProductEntity> contractUpdateList = new ArrayList<>();
            for(Map.Entry<Long, List<InstockProductEntity>> entry : instockProductMap.entrySet()) {
                Long instockId = entry.getKey();
                List<InstockProductEntity> instockProductList = entry.getValue();
                if (instockRedContractMap.containsKey(instockId)) {
                    Long redContractId = instockRedContractMap.get(instockId);
                    Map<Long, Long> productIdMap = refContractProductMap.get(redContractId);
                    if (Objects.nonNull(productIdMap)) {
                        instockProductList.forEach(item -> {
                            if (Objects.isNull(item.getRefProductId())) {
                                item.setRefProductId(productIdMap.get(item.getProductId()));
                                instockUpdateList.add(item);
                                ContractProductEntity contractProductEntity = contractProductMap.get(productIdMap.get(item.getProductId()));
                                if (Objects.nonNull(contractProductEntity)) {
                                    contractProductEntity.setInstockNum(item.getProductNum());
                                    contractUpdateList.add(contractProductEntity);
                                }
                            }
                        });
                    }
                }
            }
            if (!instockUpdateList.isEmpty()) {
                instockProductModel.updateBatch(instockUpdateList, corpid);
            }
            if (!contractUpdateList.isEmpty()) {
//                contractProductModel.updateBatch(contractUpdateList, corpid);
                Integer result = contractProductDao.updateBatch(contractUpdateList,corpid);

                List<? extends PaasFormDataEntity> paasFormDataEntities = transferSubFormHelper.transferContractProductToFormDataList(contractUpdateList);
                List<InsertDTO> insertDTOList = new ArrayList<>();
                for (PaasFormDataEntity paasFormDataEntity : paasFormDataEntities) {
                    insertDTOList.add(paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_CONTRACT_PRODUCT));
                }

//                for (ContractProductEntity entity : contractUpdateList){
//                    InsertDTO insertDTO = new InsertDTO();
//                    insertDTO.setEsId(corpid + "_" + entity.getId());
//                    insertDTO.setParent(corpid + "_" + entity.getContractId());
//                    insertDTO.setSource(BeanUtil.convertBean2Map(entity,false,true));
//                    insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_CONTRACT_PRODUCT);
//                    insertDTOList.add(insertDTO);
//                }
                paasEsModel.updateBatch(insertDTOList,WriteRequest.RefreshPolicy.WAIT_UNTIL,false);
            }
            ++ corpidCount;
            LOG.warn("公司" + corpidCount + "/" + corpidList.size());
        }
        LOG.warn("consume:" + (DateTimeUtil.getInt() - start));
        LOG.warn("操作成功");
        return null;
    }

    /**
     * 先查所有采购退货出库单-->出库单产品-->采购退货-->采购退货产品--建立ref关系
     * @param fixDataJobDTO
     * @param br
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/addRefProductIdToReturnPurchaseOutstock", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String addRefProductIdToReturnPurchaseOutstock(@RequestBody @Valid FixDataJobDTO fixDataJobDTO, BindingResult br) throws Exception {
        if (!proBaseConfig.getXbbCode().equals(fixDataJobDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
        }
        long start = DateTimeUtil.getInt();
        List<String> corpidList = fixDataJobDTO.getCorpidList();
        if (CollectionsUtil.isEmpty(corpidList)) {
            corpidList = companyModel.getCorpidList();
        }
        LOG.warn("数据库中共有公司" + corpidList.size() + "家");
        int corpidCount = 0;
        for (String corpid : corpidList) {
            BoolQueryBuilder boolQueryBuilder = boolQuery();
            boolQueryBuilder.filter(termQuery(ParameterConstant.CORPID + StringConstant.POINT + StringConstant.KEY_WORD, corpid));
            boolQueryBuilder.filter(termQuery(ParameterConstant.DEL, DelEnum.NORMAL.getDel()));
            boolQueryBuilder.filter(termQuery(OutstockEnum.getAttrConnectData(OutstockEnum.TYPE), OutstockTypeEnum.RETURNED_PURCHASE_OUTSTOCK.getCode()));
            List<String> fieldList = new ArrayList<>();
            fieldList.add(FieldTypeEnum.DATAID.getAlias());
            fieldList.add(OutstockEnum.getAttrConnectData(OutstockEnum.REF_ID));
            List<PaasFormDataEntity> outstockList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_OUTSTOCK, boolQueryBuilder, PaasFormDataEntity.class, fieldList);
            int totalCount = outstockList.size();
            LOG.warn("该公司" + corpid +"在es中共有" + totalCount + "条数据");
            List<Long> outstockIdList = new ArrayList<>();
            List<Long> returnPurchaseIdList = new ArrayList<>();
            Map<Long, Long> outstockReturnPurchaseMap = new HashMap<>(outstockList.size());
            outstockList.forEach(item -> {
                if (Objects.nonNull(item.getData()) && Objects.nonNull(item.getData().getLong(OutstockEnum.REF_ID.getAttr()))) {
                    outstockIdList.add(item.getDataId());
                    Long refId = item.getData().getLong(OutstockEnum.REF_ID.getAttr());
                    returnPurchaseIdList.add(refId);
                    outstockReturnPurchaseMap.put(item.getDataId(), refId);
                }
            });
            if (returnPurchaseIdList.isEmpty()) {
                continue;
            }
            List<OutstockProductEntity> outstockProductEntities = outstockProductModel.getProductsByOutstockIdIn(corpid, outstockIdList);
            List<ReturnedPurchaseProductEntity> returnedPurchaseProductEntities = returnedPurchaseProductModel.getReturnedPurchaseProductByReturnedPurchaseIdIn(corpid, returnPurchaseIdList);
            Map<Long, List<OutstockProductEntity>> outstockProductMap = new HashMap<>(outstockProductEntities.size());
            outstockProductEntities.forEach(item -> {
                if (Objects.isNull(item.getRefProductId())) {
                    Long key = item.getOutWarehouseId();
                    if (outstockProductMap.containsKey(key)) {
                        outstockProductMap.get(key).add(item);
                    } else {
                        List<OutstockProductEntity> list = new ArrayList<>();
                        list.add(item);
                        outstockProductMap.put(key,list);
                    }
                }
            });
            Map<Long, Map<Long, Long>> refReturnPurchaseProductMap = new HashMap<>(returnedPurchaseProductEntities.size());
            Map<Long, ReturnedPurchaseProductEntity> returnPurchaseProductMap = new HashMap<>(returnedPurchaseProductEntities.size());
            returnedPurchaseProductEntities.forEach(item -> {
                Long key = item.getReturnPurchaseId();
                if (refReturnPurchaseProductMap.containsKey(key)) {
                    refReturnPurchaseProductMap.get(key).put(item.getProductId(), item.getId());
                } else {
                    Map<Long, Long> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    map.put(item.getProductId(), item.getId());
                    refReturnPurchaseProductMap.put(key,map);
                }
                returnPurchaseProductMap.put(item.getId(), item);
            });
            List<OutstockProductEntity> outstockUpdateList = new ArrayList<>();
            List<ReturnedPurchaseProductEntity> returnedPurchaseUpdateList = new ArrayList<>();
            for(Map.Entry<Long, List<OutstockProductEntity>> entry : outstockProductMap.entrySet()) {
                Long outstockId = entry.getKey();
                List<OutstockProductEntity> outstockProductList = entry.getValue();
                if (outstockReturnPurchaseMap.containsKey(outstockId)) {
                    Long returnPurchaseId = outstockReturnPurchaseMap.get(outstockId);
                    Map<Long, Long> productIdMap = refReturnPurchaseProductMap.get(returnPurchaseId);
                    if (Objects.nonNull(productIdMap)) {
                        outstockProductList.forEach(item -> {
                            if (Objects.isNull(item.getRefProductId())) {
                                item.setRefProductId(productIdMap.get(item.getProductId()));
                                outstockUpdateList.add(item);
                                ReturnedPurchaseProductEntity returnedPurchaseProductEntity = returnPurchaseProductMap.get(productIdMap.get(item.getProductId()));
                                if (Objects.nonNull(returnedPurchaseProductEntity)) {
                                    returnedPurchaseProductEntity.setOutstockNum(item.getProductNum());
                                    returnedPurchaseUpdateList.add(returnedPurchaseProductEntity);
                                }
                            }
                        });
                    }
                }
            }
            if (!outstockUpdateList.isEmpty()) {
                outstockProductModel.updateBatch(outstockUpdateList, corpid);
            }
            if (!returnedPurchaseUpdateList.isEmpty()) {
                returnedPurchaseProductModel.updateBatch(returnedPurchaseUpdateList, corpid);
            }
            ++ corpidCount;
            LOG.warn("公司" + corpidCount + "/" + corpidList.size());
        }
        LOG.warn("consume:" + (DateTimeUtil.getInt() - start));
        LOG.warn("操作成功");
        return null;
    }

    /**
     * 修复生产单退料入库标识
     *
     * @param productDTO
     * @param br
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/fixProductionOrderReturnedFlag", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String fixProductionOrderReturnedFlag(@RequestBody @Valid ProductDTO productDTO, BindingResult br) throws Exception {
        if (!proBaseConfig.getXbbCode().equals(productDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
        }
        long start = DateTimeUtil.getInt();
        List<String> corpidList = productDTO.getCorpidList();
        if (CollectionsUtil.isEmpty(corpidList)) {
            corpidList = productionOrderModel.getCorpidList();
        }
        LOG.warn("数据库中共有公司" + corpidList.size() + "家");
        Integer index = 1;
        for (String corpid : corpidList) {
            LOG.warn(index + "/" + corpidList.size());
            BoolQueryBuilder boolQueryBuilder = boolQuery();
            boolQueryBuilder.filter(termQuery(ParameterConstant.CORPID + StringConstant.POINT + StringConstant.KEY_WORD, corpid));
            boolQueryBuilder.filter(termQuery(ParameterConstant.DEL, DelEnum.NORMAL.getDel()));
            boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD,IndexTypeEnum.IDX_SAAS_PRODUCTION_ORDER.getType()));
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            sourceBuilder.query(boolQueryBuilder);
            SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_PRODUCTION_ORDER.getIndex());
            searchRequest.source(sourceBuilder);
            Long totalCountLong = xbbElasticsearchRestTemplate.count(searchRequest, PaasFormDataEntityExt.class);
            Integer totalCount = Objects.isNull(totalCountLong) ? 0 : totalCountLong.intValue();
            LOG.warn("corpid:" + corpid + "es中共有生产单" + totalCount + "条数据");
            int pageSize = 1000;
            int totalPage = (totalCount % pageSize == 0) ? (totalCount / pageSize) : (totalCount / pageSize) + 1;
            for (int page = 0; page < totalPage; page++) {
                //设置分页
                PageRequest pageRequest = EsUtil.setPage(sourceBuilder, page, pageSize);
                XbbAggregatedPage<PaasFormDataEntityExt> esEntities = xbbElasticsearchRestTemplate.queryForPages(pageRequest,searchRequest, PaasFormDataEntityExt.class);
                if (esEntities == null) {
                    LOG.warn("corpid:" + corpid + "查询es服务器没有查到任何数据");
                }
                List<PaasFormDataEntity> orderEntityExtList = new ArrayList<>(esEntities.getContent());
                if (orderEntityExtList.isEmpty()) {
                    continue;
                }
                List<Long> orderIdIn = new ArrayList<>();
                for (PaasFormDataEntity paasFormDataEntity : orderEntityExtList) {
                    orderIdIn.add(paasFormDataEntity.getId());
                }
                boolQueryBuilder = boolQuery();
                String esData = StringConstant.JSON_DATA + StringConstant.POINT;
                boolQueryBuilder.filter(termsQuery(OutstockEnum.getEsAttr4Keyword(OutstockEnum.REF_ID), orderIdIn));
                boolQueryBuilder.filter(termQuery(OutstockEnum.getEsAttr4Keyword(OutstockEnum.TYPE), String.valueOf(OutstockTypeEnum.MATERIEL_OUTSTOCK.getCode())));
                boolQueryBuilder.filter(termQuery(StringConstant.CORPID + StringConstant.POINT + StringConstant.KEY_WORD, corpid));
                boolQueryBuilder.filter(termsQuery(FieldTypeEnum.FLOW_STATUS.getAlias(), Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(), FlowStatusEnum.PASS.getType())));
                boolQueryBuilder.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
                List<String> fieldList = new ArrayList<>();
                fieldList.add(StringConstant.SAAS_LINK_BUSINESS_ID);
                fieldList.add(OutstockEnum.getAttrConnectData(OutstockEnum.REF_ID));
                List<PaasFormDataEntityExt> outstockList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_OUTSTOCK, boolQueryBuilder, PaasFormDataEntityExt.class, fieldList);
                List<Long> outstockIdIn = new ArrayList<>();
                Map<Long, Long> stockToOrderIdMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                for (PaasFormDataEntityExt paasFormDataEntityExt : outstockList) {
                    outstockIdIn.add(paasFormDataEntityExt.getId());
                    Long refId = paasFormDataEntityExt.getData().getLong(OutstockEnum.REF_ID.getAttr());
                    if (Objects.nonNull(refId)) {
                        stockToOrderIdMap.put(paasFormDataEntityExt.getId(), refId);
                    }
                }
                Map<String,Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                param.put(ParameterConstant.CORPID, corpid);
                param.put(ParameterConstant.WAREHOUSE_ID_IN, outstockIdIn);
                param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
                // 拿到出库单的所有产品
                List<OutstockProductEntity> outstockProductEntityList= outstockProductModel.findEntitys(param);
                Map<Long, List<OutstockProductEntity>> orderOutstockProductMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                for (OutstockProductEntity entity : outstockProductEntityList){
                    Long outWarehouseId = entity.getOutWarehouseId();
                    if (stockToOrderIdMap.containsKey(outWarehouseId)) {
                        List<OutstockProductEntity> productEntityList;
                        if (orderOutstockProductMap.containsKey(stockToOrderIdMap.get(outWarehouseId))) {
                            productEntityList = orderOutstockProductMap.get(stockToOrderIdMap.get(outWarehouseId));
                        } else {
                            productEntityList = new ArrayList<>();
                        }
                        productEntityList.add(entity);
                        orderOutstockProductMap.put(stockToOrderIdMap.get(outWarehouseId), productEntityList);
                    }
                }
                Map<Long, Map<Long, Double>> orderToOutstockProductMap= new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                for (Map.Entry<Long, List<OutstockProductEntity>> entry : orderOutstockProductMap.entrySet()) {
                    Map<Long, Double> outstockProductMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    for (OutstockProductEntity outstockProductEntity : entry.getValue()) {
                        Double num = outstockProductMap.getOrDefault(outstockProductEntity.getProductId(),0D);
                        num += outstockProductEntity.getProductNum();
                        outstockProductMap.put(outstockProductEntity.getProductId(),num);
                    }
                    orderToOutstockProductMap.put(entry.getKey(), outstockProductMap);
                }
                boolQueryBuilder = boolQuery();
                boolQueryBuilder.filter(termQuery("corpid.keyword",corpid));
                boolQueryBuilder.filter(termQuery(StringConstant.DEL,DelEnum.NORMAL.getDel()));
                boolQueryBuilder.filter(termQuery(InstockEnum.getEsAttr4Keyword(InstockEnum.TYPE), String.valueOf(InstockTypeEnum.RETURNED_MATERIEL_INSTOCK.getCode())));
                boolQueryBuilder.filter(termsQuery(InstockEnum.getEsAttr4Keyword(InstockEnum.REF_ID),orderIdIn));
                boolQueryBuilder.filter(termsQuery(FieldTypeEnum.FLOW_STATUS.getAlias(), Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(), FlowStatusEnum.PASS.getType())));
                fieldList.add(InstockEnum.getAttrConnectData(InstockEnum.REF_ID));
                List<PaasFormDataEntityExt> instockList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_INSTOCK,boolQueryBuilder,PaasFormDataEntityExt.class, fieldList);
                List<Long> instockIdIn = new ArrayList<>();
                Map<Long, Long> instockToOrderIdMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                for (PaasFormDataEntityExt paasFormDataEntityExt : instockList) {
                    instockIdIn.add(paasFormDataEntityExt.getId());
                    Long refId = paasFormDataEntityExt.getData().getLong(InstockEnum.REF_ID.getAttr());
                    if (Objects.nonNull(refId)) {
                        instockToOrderIdMap.put(paasFormDataEntityExt.getId(), refId);
                    }
                }
                param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                param.put(ParameterConstant.CORPID, corpid);
                param.put(ParameterConstant.WAREHOUSE_ID_IN, instockIdIn);
                param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
                // 拿到入库单的所有产品
                List<InstockProductEntity> instockProductEntityList= instockProductModel.findEntitys(param);
                Map<Long, List<InstockProductEntity>> orderInstockProductMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                for (InstockProductEntity entity : instockProductEntityList){
                    Long intoWarehouseId = entity.getIntoWarehouseId();
                    if (instockToOrderIdMap.containsKey(intoWarehouseId)) {
                        List<InstockProductEntity> productEntityList;
                        if (orderInstockProductMap.containsKey(instockToOrderIdMap.get(intoWarehouseId))) {
                            productEntityList = orderInstockProductMap.get(instockToOrderIdMap.get(intoWarehouseId));
                        } else {
                            productEntityList = new ArrayList<>();
                        }
                        productEntityList.add(entity);
                        orderInstockProductMap.put(instockToOrderIdMap.get(intoWarehouseId), productEntityList);
                    }
                }
                Map<Long, Map<Long, Double>> orderToInstockProductMap= new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                for (Map.Entry<Long, List<InstockProductEntity>> entry : orderInstockProductMap.entrySet()) {
                    Map<Long, Double> instockProductMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    for (InstockProductEntity instockProductEntity : entry.getValue()) {
                        Double num = instockProductMap.getOrDefault(instockProductEntity.getProductId(),0D);
                        num += instockProductEntity.getProductNum();
                        instockProductMap.put(instockProductEntity.getProductId(),num);
                    }
                    orderToInstockProductMap.put(entry.getKey(), instockProductMap);
                }
                List<UpdateDataEntity> updateOrderList = new ArrayList<>();
                for (PaasFormDataEntity order : orderEntityExtList) {
                    JSONObject orderData = new JSONObject();
                    Map<Long, Double> outstockMap = orderToOutstockProductMap.get(order.getId());
                    Map<Long, Double> instockMap = orderToInstockProductMap.get(order.getId());
                    orderData.put(ProductionOrderEnum.HAS_RETURNED_MATERIEL.getAttr(), 0);
                    if (Objects.nonNull(outstockMap)) {
                        if (Objects.nonNull(instockMap)) {
                            for (Map.Entry<Long, Double> entry : instockMap.entrySet()) {
                                if (outstockMap.containsKey(entry.getKey())) {
                                    Double num = outstockMap.get(entry.getKey());
                                    if (Double.compare(entry.getValue(), num) >= 0) {
                                        outstockMap.remove(entry.getKey());
                                    }
                                }
                            }
                        }
                        if (!outstockMap.isEmpty()) {
                            orderData.put(ProductionOrderEnum.HAS_RETURNED_MATERIEL.getAttr(), 1);
                        }
                    }
                    updateOrderList.add(ExplainUtil.getUpdateData(order.getId(),orderData,corpid));
                }
                if (CollectionsUtil.isNotEmpty(updateOrderList)) {
                    productionOrderModel.updateBatch(updateOrderList,corpid);
                }
                LOG.warn("corpid:" + corpid + "es中生产单" + totalCount + "条数据" + "总共有" + totalPage + "页" + "已更新至第" + page + "页");
            }
            index ++;
        }
        LOG.warn("consume:" + (DateTimeUtil.getInt() - start));
        LOG.warn("success");

        return null;
    }

    @RequestMapping(value = "/fixBiStockChart", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String fixBiStockChart(@RequestBody @Valid ProductDTO productDTO, BindingResult br) throws Exception {
        if (!proBaseConfig.getXbbCode().equals(productDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
        }
        long start = DateTimeUtil.getInt();
        List<ChartEntity> stockChartList = chartModel.getStockChartList();
        Integer index = 0;
        PaasFormExplainEntity explainEntity;
        for (ChartEntity chartEntity : stockChartList) {
            LOG.warn("fixBiStockChart:" + index + "/" + stockChartList.size());
            index++;
            explainEntity = null;
            JSONObject driverSourcesObject = chartEntity.getDriverSources();
            SlaveSourcePojo driverSourcePojo = JSON.toJavaObject(driverSourcesObject, SlaveSourcePojo.class);
            Integer businessType = driverSourcePojo.getBusinessType();
            JSONArray slaveSources = chartEntity.getSlaveSources();
            List<SlaveSourcePojo> slaveSourcePojos = slaveSources.toJavaList(SlaveSourcePojo.class);
            List<Integer> slaveBusinessTypeList = new ArrayList<>();
            for (SlaveSourcePojo slaveSourcePojo : slaveSourcePojos) {
                slaveBusinessTypeList.add(slaveSourcePojo.getBusinessType());
            }
            if (Objects.equals(businessType, XbbRefTypeEnum.INSTOCK.getCode())) {
                if (slaveBusinessTypeList.contains(XbbRefTypeEnum.PURCHASE.getCode())) {
                    explainEntity = paasFormExplainModel.getByBusinessType(XbbRefTypeEnum.PURCHASE_INSTOCK.getCode(), chartEntity.getCorpid());
                    driverSourcePojo.setBusinessType(XbbRefTypeEnum.PURCHASE_INSTOCK.getCode());
                    driverSourcePojo.setAppId(explainEntity.getAppId());
                    driverSourcePojo.setMenuId(explainEntity.getMenuId());
                    driverSourcePojo.setFormId(explainEntity.getFormId());
                    chartEntity.setDriverSources(JSON.parseObject(JSON.toJSON(driverSourcePojo).toString()));
                }
            }
            if (Objects.equals(businessType, XbbRefTypeEnum.OUTSTOCK.getCode())) {
                if (slaveBusinessTypeList.contains(XbbRefTypeEnum.CONTRACT.getCode())) {
                    explainEntity = paasFormExplainModel.getByBusinessType(XbbRefTypeEnum.CONTRACT_OUTSTOCK.getCode(), chartEntity.getCorpid());
                    driverSourcePojo.setBusinessType(XbbRefTypeEnum.CONTRACT_OUTSTOCK.getCode());
                    driverSourcePojo.setAppId(explainEntity.getAppId());
                    driverSourcePojo.setMenuId(explainEntity.getMenuId());
                    driverSourcePojo.setFormId(explainEntity.getFormId());
                    chartEntity.setDriverSources(JSON.parseObject(JSON.toJSON(driverSourcePojo).toString()));
                } else if (slaveBusinessTypeList.contains(XbbRefTypeEnum.PRODUCTION_ORDER.getCode())) {
                    explainEntity = paasFormExplainModel.getByBusinessType(XbbRefTypeEnum.PRODUCTION_MATERIEL_OUTSTOCK.getCode(), chartEntity.getCorpid());
                    driverSourcePojo.setBusinessType(XbbRefTypeEnum.PRODUCTION_MATERIEL_OUTSTOCK.getCode());
                    driverSourcePojo.setAppId(explainEntity.getAppId());
                    driverSourcePojo.setMenuId(explainEntity.getMenuId());
                    driverSourcePojo.setFormId(explainEntity.getFormId());
                    chartEntity.setDriverSources(JSON.parseObject(JSON.toJSON(driverSourcePojo).toString()));
                }
            } else if (Objects.equals(businessType, XbbRefTypeEnum.RETURNED_PURCHASE.getCode())) {
                if (slaveBusinessTypeList.contains(XbbRefTypeEnum.OUTSTOCK.getCode())) {
                    explainEntity = paasFormExplainModel.getByBusinessType(XbbRefTypeEnum.RETURNED_PURCHASE_OUTSTOCK.getCode(), chartEntity.getCorpid());
                    for (SlaveSourcePojo slaveSourcePojo : slaveSourcePojos) {
                        if (Objects.equals(slaveSourcePojo.getBusinessType(), XbbRefTypeEnum.OUTSTOCK.getCode())) {
                            slaveSourcePojo.setBusinessType(XbbRefTypeEnum.RETURNED_PURCHASE_OUTSTOCK.getCode());
                            slaveSourcePojo.setAppId(explainEntity.getAppId());
                            slaveSourcePojo.setMenuId(explainEntity.getMenuId());
                            slaveSourcePojo.setFormId(explainEntity.getFormId());
                        }
                    }
                    chartEntity.setSlaveSources(JSON.parseArray(JSON.toJSON(slaveSourcePojos).toString()));
                }
            }
            chartModel.update(chartEntity);
        }
        LOG.warn("consume:" + (DateTimeUtil.getInt() - start));
        LOG.warn("success");
        return null;
    }
}
